<script lang="ts" setup>
	import {
		ref,
		computed,
		reactive,
		watch
	} from 'vue'
	import dateTime from '@/static/js/date.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import article from '@/api/article.js'
	import {
		useStore
	} from 'vuex'
	import base from '@/api/baseUrl.js'
	import def from '@/static/js/throttleAndDebounce.js'
	import user from '@/api/user.js'
	import chat from '@/api/chat';
	const store = useStore()
	interface userObj {
		[propName : string] : any
	}
	interface Props {
		list : any[],
		swiperCurrent : string | number,
		navList : any[],
		triggered ?: boolean
		status ?: string
	}
	const baseUrl = base + '/'
	const props = withDefaults(defineProps<Props>(), {
		list: () => [],
		swiperCurrent: 0,
		navList: () => [],
		triggered: false,
		status: 'loading'
	})
	let allState = reactive({
		list: [],
		userinfo: uni.getStorageSync('userinfo'),//自己的
		crowdList: [],
	})
	let text = ref('转发')
	let userinfo = uni.getStorageSync('userinfo')
	const emit = defineEmits(['listSwitch', 'onPulling', 'onAbort', 'onRefresh', 'onRestore', 'giveLike', 'scrolltolower'])
	let player = ref(null)
	let all = reactive({
		popupIsShow: false,
		sharePopup: false,
		chosseObj: {},
		screenHeight: 0,
		direction: false,
		friends: false,
		shareIcon: [
			{
				title: '私聊和群',
				icon: 'email-fill',
				id: 0,
				color: 'rgb(255,205,0)',
				name: 'friends'
			},
			{
				title: 'qq好友',
				icon: 'qq-circle-fill',
				id: 1,
				color: 'skyblue',
				name: 'qq'
			},
			{
				title: '微信好友',
				icon: 'weixin-circle-fill',
				id: 2,
				color: 'rgb(93,241,126)',
				name: 'wx'
			},
			{
				title: '朋友圈',
				icon: 'moments',
				id: 3,
				color: 'skyblue',
				name: 'pyq'
			}
		]
	})
	const skip = (str : string) => {
		uni.navigateTo({
			url: str,
		})
	}
	let loadText = ref({
		loadmore: '上拉加载更多',
		loading: '努力加载中',
		nomore: '我是有底线的'
	})
	watch(() => props.list, (newArr) => {
		for (let i = 0; i < newArr.length; i++) {
			newArr[i].popupIsShow = false
		}
	})
	//swiper/tabs当前页
	//swiper切换事件
	const listSwitch = (value : any) => {
		// #ifdef H5
		player.value?.pause()
		// #endif

		emit('listSwitch', value.detail)
	}
	//下拉刷新触发
	const onPulling = (value : any) => {
		if (value.detail.deltaY < 0) return
		emit('onPulling', value)

	}
	//中止触发
	const onAbort = (value : any) => {
		emit('onAbort', value)
	}
	//刷新触发
	const onRefresh = (value : any) => {
		emit('onRefresh', value)
	}
	//复位
	const onRestore = (value : any) => {
		emit('onRestore', value)
	}
	//上拉刷新
	const scrolltolower = () => {
		emit('scrolltolower')
	}
	//转发
	const handleForward = (item : any) => {
		item.popupIsShow = false
		store.commit('chatUser', all.chosseObj)
		if (item.video) {
			uni.navigateTo({
				url: `/pages_home/sendVideo/index?type=1`,
				success: () => {
					item.popupIsShow = false
				}
			})
		} else {
			uni.navigateTo({
				url: `/pages_home/writeArticle/index?type=1`,
				success: () => {
					item.popupIsShow = false
				}
			})
		}

	}
	const edit = (item : any, e : any) => {
		store.commit('chatUser', item)
		if (all.screenHeight - e.detail.y < 200) {
			all.direction = true
		} else {
			all.direction = false
		}
		all.chosseObj = item
		let url = ``
		//用户自己编辑
		if (item.authorid === userinfo.userid) {
			if (item.typeid == 3) {	//视频
				if (item.list && item.list.length) {
					url = `/pages_home/sendVideo/index?type=2&id=${item.id}`
				} else {
					url = `/pages_home/sendVideo/index?id=${item.id}&video=${item.video}`
				}
			} else {
				if (item.list && item.list.length) {
					url = `/pages_home/writeArticle/index?type=2&id=${item.id}`
				} else {
					url = `/pages_home/writeArticle/index?id=${item.id}&img=${item.img}`
				}

			}
			uni.navigateTo({
				url: url,
				success: () => {
					setTimeout(() => {
						uni.$emit('update', item)
					}, 100)
				}
			})
		} else { //不是本人就转发
			all.popupIsShow = true
			item.popupIsShow = !item.popupIsShow
		}
	}
	const filterDate = computed(() => (item : any) => {
		return dateTime.timeago(new Date(item))
	})
	const onloadCode = (videos : string) => {
		let text = `
			const url = "${baseUrl}${videos}"
			this.contentWindow.document.body.innerHTML = '<video style="width: 100%;height: 100%" controls="controls" src="'+url+'" preload="auto" poster="http://boo.nat300.top/1681214822070-.jpg"></video>'  
			const iframe = top.document.getElementsByTagName('iframe')[0]  
			var evObj = document.createEvent('MouseEvents')
			evObj.initEvent( 'event1', true, false )
			iframe.dispatchEvent(evObj)
		`
		return text
	}
	//点赞
	const giveLike = async (id : number, authorid : number, item : userObj) => {
		if (authorid == userinfo.userid) return uni.showToast({
			title: '不能给自己点赞',
			icon: 'none'
		})
		const res = await article.giveLike({
			articleid: id,
			userid: authorid
		})
		if (res.msg === '点赞成功') {
			item.isdz = 1
		} else if (res.msg === '取消成功') {
			item.isdz = 0
		}
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
		emit('giveLike')
		//0赞了，1未赞
	}

	const followList = async () => {
		const res = await user.getUserList({
			username: ''
		})
		allState.list = res.data
		getCrowdList()
	}
	const getCrowdList = async () => {
		const res = await chat.getCrowdList()
		allState.crowdList = res.data
	}
	//分享
	const handleshare = (item : any) => {
		all.sharePopup = true
		item.popupIsShow = false
	}
	/* 
		*	provider weixin qq
		*  scene WXSceneSession(分享到聊天界面) WXSceneTimeline(分享到朋友圈) WXSceneFavorite(分享到微信收藏)
		*  type 0(图文) 1(纯文字)  2(纯图片) 3(音乐) 4(视频)
		*/
	const handleshareEvent = (item : userObj) => {
		switch (item.id) {
			case 0:	//app好友
				all.friends = true
				item.popupIsShow = false
				followList()
				break
			case 1:	//qq好友
				sendShare('qq', '', 1)
				break
			case 2:	//微信好友
				sendShare('weixin', 'WXSceneSession', 1)
				break
			case 3:	//朋友圈
				sendShare('weixin', 'WXSceneTimeline', 1)
				break
			default:
				uni.showToast({
					title: '暂无功能',
					icon: 'none'
				})
		}
	}
	const send = (item : userObj) => {
		console.log(item, all.chosseObj)
	}
	const sendShare = (provider : any, scene : any, type : any) => {
		// #ifndef H5
		return new Promise((reslove, reject) => {
			uni.share({
				provider: provider,
				scene: scene,
				type: type,
				summary: "你值得拥有",
				success: function (res) {
					console.log("success:" + JSON.stringify(res))
					// @ts-ignore
					reslove()
				},
				fail: function () {
					reject()
				}
			})
		})
		// #endif
	}
	const preview = (img) => {
		
		uni.previewImage({
			urls: [img],
			current: 1,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function (data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function (err) {
					console.log(err.errMsg);
				}
			}
		});
	}
	onLoad(() => {
		// #ifndef H5
		player.value = uni.createVideoContext("video")
		// #endif
		all.screenHeight = uni.getSystemInfoSync().screenHeight
	})
</script>

<template>
	<swiper :current="swiperCurrent" @change="listSwitch" class="swiper" :duration="300">
		<swiper-item class="swiper-item" v-for="index in navList.length" :key='index'>

			<scroll-view class="scroll" scroll-y :refresher-triggered="triggered" :refresher-threshold="100"
				refresher-enabled @refresherabort="onAbort" @refresherrestore="onRestore" @refresherrefresh="onRefresh"
				@refresherpulling="onPulling" @scrolltolower='def.debounce(scrolltolower,1000,true)'>
				<!--  -->
				<!-- 文章列表 -->
				<view class="card-list" v-for="(item) in list" :key="item.id">
					<!-- 标题 -->
					<view class="card-list-top flex flex-ai-c" @click.stop="skip(`/pages_home/detail?id=${item.id}`)">
						<!-- 头像 -->
						<view class="head-img" @click.stop="skip(`/pages_home/personalInfo/index?id=${item.authorid}`)">
							<image v-if="item.handimg" :src="item.handimg"></image>
							<image v-else src="../static/img/headimg.jpg"></image>
						</view>
						<view class="userinfo" style="flex: 1;">
							<view class="flex flex-jc-sb">
								<view class="name">{{item.username}}</view>
								<view>
									<u-icon size="36rpx" name="arrow-down" color="rgb(175,177,181)"></u-icon>
								</view>
							</view>
							<view class="date">{{filterDate(item.pubdate)}}</view>
						</view>

					</view>
					<!-- 文章 forwardid-->
					<view class="card-list-bottom" @click="skip(`/pages_home/detail?id=${item.id}`)">
						<view class="description">
							<rich-text :nodes="item.content"></rich-text>
						</view>
						<view class="video" v-if="item.img||item.video">
							<image v-if="item.img" mode="aspectFill" :src="item.img" @click.stop="preview(item.img)">
							</image>
							<!-- #ifdef APP-PLUS -->
							<iframe v-else-if="item.video" :onload="onloadCode(item.video)" src="about:blank"
								style="height: 100%;width: 100%"></iframe>
							<!-- #endif -->
							<!-- #ifndef APP-PLUS -->
							<video id="video" v-else-if="item.video" :src="item.video"></video>
							<!-- #endif -->
						</view>
					</view>
					<!-- 转发 -->
					<template v-if="item.forwardid">
						<view class="card-list-bottom" style="background-color: whitesmoke;" v-for="item2 in item.list">
							<view class="description" @click="skip(`/pages_home/detail?id=${item2.id}`)">
								<text @click.stop="skip(`/pages_home/personalInfo/index?id=${item2.authorid}`)"
									style="color: rgb(237, 115, 37)">@{{item2.username}}</text>
								<rich-text :nodes="item2.content"></rich-text>
							</view>
							<view class="video" v-if="item2.img||item2.video">
								<image v-if="item2.img" mode="aspectFill" :src="item2.img" @click.stop="preview(item2.img)">
								</image>
								<!-- #ifdef APP-PLUS -->
								<iframe v-else-if="item2.video" :onload="onloadCode(item2.video)" src="about:blank"
									style="height: 100%;width: 100%"></iframe>
								<!-- #endif -->
								<!-- #ifndef APP-PLUS -->
								<video id="video" v-else-if="item2.video" :src="item2.video"></video>
								<!-- #endif -->
							</view>
						</view>
					</template>

					<!-- set -->
					<view class="card-list-set flex flex-jc-sa flex-ai-c">
						<view class="set-icon" @click.stop="edit(item,$event)">
							<u-icon size="36rpx" name="zhuanfa" color="#000"></u-icon>
							<text>{{item.authorid == userinfo.userid?'编辑':'转发'}}</text>
							<!-- 分享框 -->
							<view class="share" v-if="item.popupIsShow" :style="[all.direction? 'bottom: 45rpx':'']"
								style="border-radius: 12rpx;">
								<view @click.stop="handleForward(item)">转发</view>
								<view @click.stop="handleshare(item)">分享</view>
							</view>
							<view v-if="item.popupIsShow" style="width: 100%;height: 100%;
								position: fixed;background: rgba(0,0,0,0.3);
								z-index: 999;left: 0;top: 0;" @click="all.popupIsShow = false">
							</view>
						</view>
						<view class="set-icon" @click.stop="skip(`/pages_home/detail?id=${item.id}&type=${1}`)">
							<u-icon size="36rpx" name="more-circle" color="#000"></u-icon>
							<text>评论</text>
						</view>
						<view class="set-icon" @click.stop="giveLike(item.id,item.authorid,item)">
							<u-icon size="36rpx" name="thumb-up" :color="item.isdz?'red':'#000'"></u-icon>
							<text>赞</text>
						</view>
					</view>

				</view>
				<u-loadmore :status="status" @loadmore="scrolltolower" :load-text="loadText" />
			</scroll-view>
		</swiper-item>
	</swiper>

	<u-popup v-model="all.sharePopup" mode="bottom">
		<view style="text-align: center;padding: 20rpx 0;">分享</view>
		<view class="flex flex-ai-c flex-jc-sa flex-wrap-w">
			<view v-for="item in all.shareIcon" :key="item.id" style="text-align: center;"
				@click="handleshareEvent(item)">
				<view>
					<u-icon :name="item.icon" size="60" :color="item.color"></u-icon>
				</view>
				<view>{{item.title}}</view>
			</view>
		</view>
		<view class="flex flex-jc-c btn">
			<view class="btn-text" @click="all.sharePopup = false">取消分享</view>
		</view>
	</u-popup>

	<u-popup v-model="all.friends" mode="center" border-radius="20">
		<view style="text-align: center;padding: 20rpx 0;">选择聊天好友</view>
		<view style="width: 80vw;height: 70vh" class="list">
			<!-- 群消息或or好友消息 -->
			<view v-for="item in allState.list" :key="item.userid" @click="send(item)">
				<view class="flex flex-ai-c list-item">
					<image :src="item.handimg"></image>
					<view class="f1 list-item-info flex flex-dir-c flex-jc-c">
						<view>{{item.nickname || item.username}}</view>
					</view>
					<view class="list-time flex flex-dir-c flex-ai-c" style="text-align: center;">
						<view>{{item.time || null}}</view>
						<view v-if="item.msgNum"
							style="background-color: red;width: 30rpx;height: 30rpx;color: #fff;border-radius: 50%;">
							{{item.msgNum >= 100 ? 99: item.msgNum}}
						</view>
					</view>
				</view>
			</view>
			<view style="margin: 20rpx;">群列表</view>
			<!-- 群 -->
			<view v-for="item in allState.crowdList" :key="item.id" @click="send(item)">
				<view class="flex flex-ai-c list-item">
					<image :src="item.img"></image>
					<view class="f1 list-item-info flex flex-dir-c flex-jc-c">
						<view>{{item.title}}</view>
					</view>
					<view class="list-time flex flex-dir-c flex-ai-c" style="text-align: center;">
						<view>{{item.time || null}}</view>
						<view v-if="item.msgNum"
							style="background-color: red;width: 30rpx;height: 30rpx;color: #fff;border-radius: 50%;">
							{{item.msgNum >= 100 ? 99: item.msgNum}}
						</view>
					</view>
				</view>
			</view>
		</view>
	</u-popup>
</template>
<style lang="scss" scoped>
	html,
	page {
		height: 100%;
	}

	.list {

		:deep(.u-icon) {
			padding: 20rpx;
			border-radius: 50%;
			color: #fff;
			background-color: orange;
		}

		&-item {
			height: 120rpx;
			margin: 0 20rpx;
			position: relative;

			&-font {
				border-bottom: 1rpx solid rgb(222, 225, 230);
				margin-left: 20rpx;
				height: 100%;
				line-height: 120rpx;
			}

			&-info {
				border-bottom: 1rpx solid rgb(222, 225, 230);
				margin-left: 20rpx;
				height: 100%;
			}
		}

		&-time {
			position: absolute;
			right: 0;
			top: 30rpx;
			font-size: 20rpx;
		}
	}

	.btn {
		padding: 20rpx 0;

		&-text {
			width: 90%;
			height: 70rpx;
			box-shadow: 0 0 10rpx rgb(175, 177, 181);
			border-radius: 36rpx;
			text-align: center;
			line-height: 70rpx;
		}
	}

	.share {
		position: absolute;
		background-color: #fff;
		box-shadow: 0px 0px 10rpx rgb(175, 177, 181);
		z-index: 1000;
		padding: 10rpx 20rpx;
		line-height: 60rpx;
	}

	.swiper {
		height: 100%;

		.swiper-item {
			.scroll {
				width: 100%;
				height: 100%;

				//列表
				.card-list {

					background-color: #fff;
					padding: 20rpx 20rpx 0 20rpx;
					margin-bottom: 20rpx;

					&-top {
						.userinfo {
							margin: 0 20rpx;

							.name {
								font-size: 32rpx;
								color: rgb(237, 115, 37);
							}

							.date {
								font-size: 20rpx;
							}
						}
					}

					&-bottom {
						margin: 20rpx 0;
						color: #000;
						font-weight: 400;

						.video {
							width: 100%;
							height: 500rpx;

							image {
								width: 100%;
								height: 100%;
							}

							video {
								position: relative;
								width: 100%;
								height: 100%;
							}
						}
					}

					&-set {
						border-top: 1px solid rgb(200, 200, 200);
						height: 80rpx;

						.set-icon {
							vertical-align: middle;
							position: relative;

							text {
								margin-left: 10rpx;
							}
						}
					}
				}
			}
		}
	}

	.tabs {
		width: 100%;
	}

	.description {
		display: -webkit-box;
		overflow: hidden;
		text-overflow: ellipsis;
		-webkit-line-clamp: 8;
		-webkit-box-orient: vertical;
	}
</style>